import { Component, ViewChild } from '@angular/core';
import { EditStoreHouseComponent } from '../../storehouse/edit-store-house/edit-store-house.component';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { UserService } from 'src/app/@core/services/user/user.service';
import { Router } from '@angular/router';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { AddPositionComponent } from '../add-position/add-position.component';
import { EditPositionComponent } from '../edit-position/edit-position.component';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-position',
  templateUrl: './position.component.html',
  styleUrls: ['./position.component.scss']
})
export class PositionComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  SearchTerm:string=null;
  pageSizeOptions = [10, 20, 30, 50, 100];
  treeData:any;
  allCheckedStatus = false;
  checkedIds = [];
  deleteIDs = [];
  editemployeeId:""
  msgs: Array<Object> = [];
  option:any={}//部门option
  departmentId:any;//部门id
  pathPids=[]//部门树结构路径
  employData:any[]=[];//员工数据
  config = {
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  searchDepartmentValue:any=''
  filteredTreeNodes:any
  displayTreeData: any[];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '仓位编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓位名称',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '二维码',
        fieldType: 'text',
      },
      {
        filed:'enabled',
        header:'状态',
        fieldType:'boolean'
      }
    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field:'name',
      width:'200px'
    },
    {
      field:'name',
      width:'100px'
    },
    {
      field:'name',
      width:'100px'
    },
    {
      field:'name',
      width:'130px'
    },
    {
      field:'name',
      width:'100px'
    },
  ];//表格宽度配置
  selectoptions = [
    '全部','启用','禁用'
  ]
  selectvalue = '全部'
  tabledata = []
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }
    ) datatable!: DataTableComponent;//获取table
  displayTableData: any[];
  Status!: string;
  file: any;
  warehouseId: any;
  searchWarehouseValue: any;
  constructor(private dialogService: DialogService,private UserService:UserService,private Router:Router,private SharedMethodService:SharedMethodService,private StorehouseService:StorehouseService){}
  ngOnInit(): void {
    this.Status = this.selectvalue=='全部'?"all":this.selectvalue=='启用'?"enable":"disable"
    this.StorehouseService.getAllWarehouses().subscribe((data:any)=>{
      this.treeData=data
      this.displayTreeData = [{ warehouseName: '全部',warehouseId:null}, ...this.treeData];
      if( this.treeData.length>0){
        this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
          this.tabledata=data.items
          this.displayTableData = this.tabledata;
          this.pager.total=data.totalCount;
        })
      }
    })
  }
  afterTreeInit($event: any){
    if($event["null"]){
      $event["null"].data.isActive=true
    }
  }//树形菜单初始化
  nodeSelected($event:any){
    this.option=$event.data.originItem
    this.warehouseId = $event.data.originItem.warehouseId;
    if(this.warehouseId){
      this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
        this.displayTableData = this.tabledata;
        this.pager.total=data.totalCount;
      })
    }else{
      this.StorehouseService.getAllPositions().subscribe((data:any)=>{
        this.tabledata=data
        this.displayTableData = this.tabledata;
      })
    }
  }//树形菜单点击事件
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  searchWarehouse($event:any){
    this.searchWarehouseValue = $event.target.value
    if (this.searchWarehouseValue === '') {
      // 如果用户输入的值为空，显示原先的数据
      this.displayTreeData = this.displayTreeData = [{ warehouseName: '全部',warehouseId:null}, ...this.treeData];
    } else {
      // 否则，显示过滤后的数据
      this.filteredTreeNodes = [...this.treeData].filter((node:any) => node.warehouseName.includes(this.searchWarehouseValue));
      this.displayTreeData = this.filteredTreeNodes;
    }
  }//搜索仓库
  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
    this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }//切换页码
  pageSizeChange($event: any){
    this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }//改变每页显示数量
  creatPositon(dialogtype?: string){
    let data = {
      options: this.treeData,
      option:this.option,
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '新建仓位',
      data:data,
      content: AddPositionComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.Position.positionName&&results.modalContentInstance.Position.positionNum&&results.modalContentInstance.Position.warehouseId){
              this.StorehouseService.createPosition(results.modalContentInstance.Position).subscribe((data:any)=>{
                this.showToast('success','成功','仓库创建成功')
                results.modalInstance.hide();
                this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.tabledata=data.items
                  this.displayTableData = this.tabledata;
                  this.pager.total=data.totalCount;
                })
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新建仓位
  disable(){
    this.StorehouseService.disablePositions(this.checkedIds).subscribe((data:any)=>{
      this.showToast('success','成功','禁用成功')
      this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
        this.displayTableData = this.tabledata;
        this.pager.total=data.totalCount;
        this.checkedIds = []
        this.deleteIDs = []
      })
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//禁用仓位
  enable(){
    this.StorehouseService.enablePositions(this.checkedIds).subscribe((data:any)=>{
      this.showToast('success','成功','启用成功')
      this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
        this.displayTableData = this.tabledata;
        this.pager.total=data.totalCount;
        this.checkedIds = []
        this.deleteIDs = []
      })
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//启用仓位
  delete(id:any,dialogtype?: string ){
    const results = this.dialogService.open({
      id: 'department',
      data: { id: id },
      ...this.config,
      title: '删除仓库',
      content: '确认删除当前选中的仓位？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.StorehouseService.deletePosition(id).subscribe((data:any)=>{
              this.showToast('success','成功','删除成功')
              results.modalInstance.hide();
              this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                this.tabledata=data.items
                this.displayTableData = this.tabledata;
                this.pager.total=data.totalCount;
              })
            },(error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
            }
          )
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        }
      ],
    });
  }//删除仓位
  deletes(dialogtype?:string){
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '删除仓库',
      content: '确认删除当前选中的仓位？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.StorehouseService.deletePositions(this.checkedIds).subscribe((data:any)=>{
              this.showToast('success','成功','删除成功')
              results.modalInstance.hide();
              this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                this.tabledata=data.items
                this.displayTableData = this.tabledata;
                this.pager.total=data.totalCount;
                this.checkedIds = []
                this.deleteIDs = []
              })
            },(error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
            }
          )
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        }
      ],
    });
  }
  edit(rowItem:any,dialogtype?: string,){
    let data = {
      options: this.treeData,
      rowItem:rowItem,
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '更新仓位',
      data:data,
      content: EditPositionComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.positionNum&&results.modalContentInstance.Position.positionName){
              this.StorehouseService.updatePosition(results.modalContentInstance.positionID,results.modalContentInstance.Position).subscribe((data:any)=>{
                this.showToast('success','成功','仓位更新成功')
                results.modalInstance.hide();
                this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.tabledata=data.items
                  this.displayTableData = this.tabledata;
                  this.pager.total=data.totalCount;
                })
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//编辑仓库
  selctChange(){
    this.Status = this.selectvalue=='全部'?"all":this.selectvalue=='启用'?"enable":"disable"
    setTimeout(() => {
      this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
        this.displayTableData = this.tabledata;
        this.pager.total=data.totalCount;
      })
    }, 100);
  }//下拉框选择
  search(){
    this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }//搜索
  reset(){
    this.Status = null
    this.selectvalue = '全部'
    this.departmentId = null
    this.searchDepartmentValue = ''
    this.SearchTerm = ''
    this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
        this.displayTableData = this.tabledata;
        this.pager.total=data.totalCount;
      })
  }//重置
  downloadPositionFileModel(){
    this.StorehouseService.downloadPositionFileModel().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '仓位模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载模板
  // ImportUsersFromExcel(){
  //
  // }//导入员工
  @ViewChild('fileInput1') fileInput1: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput1.nativeElement.click();
  }
  onFileSelected(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.StorehouseService.importPositionsFromExcel(this.file).subscribe((data:any)=>{
          this.showToast('success','成功','导入成功')
          this.StorehouseService.getPositons(this.warehouseId,this.Status,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
            this.tabledata=data.items
            this.displayTableData = this.tabledata;
          })
        },(error) => {
          if(error.status==404){
            this.showToast('error', '失败', '服务器连接失败');
          }else{
            this.showToast('error', '失败', error.error);
          }
        })
  }
  DownloadFile(){
    this.StorehouseService.downloadPositionFile().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '仓位信息.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载员工信息
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }){
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable,'positionId').subscribe((data:any)=>{
      this.deleteIDs=data;
    })
    this.SharedMethodService.getCheckedRows(this.datatable,'positionId').subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }//获取选中行
  cleared(){
    this.SharedMethodService.cleared(this.deleteIDs,this.tabledata,this.datatable).subscribe((data:any)=>{
      this.deleteIDs=data;
    })
  }//清空选中行
  ImportDepartmentsFromExcel(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.UserService.ImportDepartmentsFromExcel(this.file).subscribe((data:any)=>{
          this.showToast('success','成功','导入成功')
          this.UserService.GetAllDepartments(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
            this.treeData=data.items
            this.displayTreeData = [{ name: '全部' ,departmentId:null}, ...this.treeData];
            if( this.treeData.length>0){
              this.UserService.GetAllEmploy(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                this.tabledata=data.items;
                this.displayTableData = this.tabledata;
                this.pager.total=data.totalCount;
                let departmentIdToName = {};
                this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
                departmentIdToName[item.departmentId] = item.name;
                });
                this.tabledata.forEach(item => {
                  if (item.departmentId in departmentIdToName) {
                    item.departmentId = departmentIdToName[item.departmentId];
                  }
                });
              })
            }
          })
        },(error) => {
          if(error.status==404){
            this.showToast('error', '失败', '服务器连接失败');
          }else{
            this.showToast('error', '失败', error.error);
          }
        })
  }
  getImagesArray2(fileURL: string): string[] {
      let urls = fileURL.split(',');
      urls = urls.map(url => environment.modifiedApiUrl +'/' + url);
      return urls;
    }
}
